import { createRouter, createWebHashHistory } from 'vue-router'
import Index from '@/views/index/index.vue'

const globalVal = globalThis as any;



const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Index',
      component: Index,
      meta:{
        keepAlive: true
      }
    }
  ],
})



// 上一个路由
let prevRoute:any|null = null;
router.beforeEach((to, from, next) => {
  const prevFullPath = (prevRoute && prevRoute.from) ? prevRoute.from.fullPath : '';
  if(prevFullPath == to.fullPath){
    prevRoute = null
  }
  else{
    prevRoute = {from, to}
  }
  next();
})

globalVal.navigateTo = (config:any) => {
  const route = router.currentRoute.value;
  if(route && route.fullPath ===  config.url){
      return ;
    }

    const prevFullPath = (prevRoute && prevRoute.from) ? prevRoute.from.fullPath : '';

    // 如果同一个path 只是参数不一样，直接使用replace
    if(route && route.path == config.url.split('?')[0]){
      router.replace(config.url)
    }
    else if(prevFullPath === config.url){

      router.back();

    }
    else{
      router.push(config.url)
    }
}

globalVal.back = () => {

    if(globalVal.history.state.back === null){
      router.replace('/')
    }
    else{
      console.log('back')
      router.back();
    }
}

export default router
